package com.gupaoedu.spring.framework.webmvc.servlet;

import com.gupaoedu.spring.framework.annotation.*;
import com.gupaoedu.spring.framework.context.GPApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * @author fan
 * @version 1.0v
 * @Description TODO
 * @Time 2020-11-20 00:33
 * @Email 44867924@qq.com
 */
public class GPDispatcherServlet extends HttpServlet {

    /**
     * 读取properties的工具类 java自带
     */
    private Properties contextConfig = new Properties();

    /**
     * 用来存所有的扫描到的类的全类名
     */
    private List<String> classNames = new ArrayList<>();

    /**
     * handlerMapper容器
     */
    private Map<String, Method> handlerMapper = new HashMap<>();

    private GPApplicationContext applicationContext;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //　运行阶段
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception,Detail:" + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = ("/" + url).replaceAll(contextPath, "").replaceAll("/+", "/");
        if (!this.handlerMapper.containsKey(url)) {
            resp.getWriter().write("404 Not Found");
            return;
        }
        Map<String, String[]> paramsMap = req.getParameterMap();
        Method method = this.handlerMapper.get(url);
        // 还是利用反射，首先拿到形参列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        // 定义实参列表
        Object[] paramsValues = new Object[parameterTypes.length];
        // 根据形参列表给实参列表赋值
        for (int i = 0; i < parameterTypes.length; i++) {
            Class parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class) {
                paramsValues[i] = req;
            } else if (parameterType == HttpServletResponse.class) {
                paramsValues[i] = resp;
            } else if (parameterType == String.class) {
                // 拿到注解
                Annotation[][] pa = method.getParameterAnnotations();
                for (Annotation a : pa[i]) {
                    if (a instanceof GPRequestParam) {
                        String paramName = ((GPRequestParam) a).value();
                        if (!"".equals(paramName.trim())) {
                            String value = Arrays.toString(paramsMap.get(paramName))
                                    .replaceAll("\\[|\\]", "")
                                    .replaceAll("\\s", "");
                            paramsValues[i] = value;
                        }
                    }
                }
            }
        }
        method.invoke(this.applicationContext.getBean(method.getDeclaringClass()), paramsValues);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {

        // 1 程序初始化　读取配置文件　　　这里是去读取web.xml <param-name>contextConfigLocation</param-name> 得到的值是　application.properties
        applicationContext = new GPApplicationContext(config.getInitParameter("contextConfigLocation"));

        // ==========   mvc   =============
        //5 初始化handlerMapper
        doInitHanderMapper();
        // 初始化阶段完成
        System.out.println("GP spring framework is init");
    }

    private void doInitHanderMapper() {
        if (this.applicationContext.getBeanDefinitionCount() == 0) {
            return;
        }
        String[] beanNames = this.applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            Object instance = this.applicationContext.getBean(beanName);
            Class<?> clazz = instance.getClass();
            if (!clazz.isAnnotationPresent(GPController.class)) {
                continue;
            }
            // 如果还有直接加到类上的
            String baseUrl = "";
            if (clazz.isAnnotationPresent(GPRequestMapping.class)) {
                GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);
                baseUrl = requestMapping.value();
            }
            // 得到所有的public 方法
            for (Method method : clazz.getMethods()) {
                System.out.println(method.isAnnotationPresent(GPRequestMapping.class));
                if (!method.isAnnotationPresent(GPRequestMapping.class)) {
                    return;
                }
                GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);
                // 防止多个斜线
                String url = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                handlerMapper.put(url, method);
                System.out.println("Mapper : " + url + "," + method);
            }
        }
    }

    private void doLoadConfig(String contextConfgLocation) {
        // 加载配置文件
        // 在classPath去找
        // 变成一个文件流
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfgLocation);
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doSanner(String scanPackage) {
        // 用正则，把点变成'/'
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        // 把这个url变成一个文件
        //得到这个文件的路径
        File classPth = new File(url.getFile());
        for (File file : classPth.listFiles()) {
            // 这里的file有文件，也有文件夹
            if (file.isDirectory()) {
                doSanner(scanPackage + "." + file.getName());
            } else {
                // 一个文件夹下面会有各种各样的文件 这里只要以.class结尾的文件
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                // 得到他的全类名
                String fileName = (scanPackage + "." + file.getName().replace(".class", ""));
                classNames.add(fileName);
            }
        }
    }
}

